package com.uniview.mvpdemo.view;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.uniview.mvpdemo.R;
import com.uniview.mvpdemo.base.BaseActivity;
import com.uniview.mvpdemo.bean.Login;
import com.uniview.mvpdemo.mvp.MainContract;
import com.uniview.mvpdemo.mvp.MainPresenter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements MainContract.View {
    public static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.user)
    EditText user;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.clear)
    Button clear;
    @BindView(R.id.login)
    Button login;

    private MainContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        new MainPresenter(this);
    }

    @OnClick({R.id.clear, R.id.login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear:
                presenter.doClear();
                break;
            case R.id.login:
                String username = user.getText().toString();
                String pwd = password.getText().toString();
                presenter.doLogin(username, pwd);
                break;
        }
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onLoading(String text) {
        showLoading(text);
    }

    @Override
    public void loadingComplete() {
        hideLoading();
    }

    @Override
    public void loadingError(String error) {
    }

    @Override
    public void clearEdit() {
        user.setText(null);
        password.setText(null);

        user.requestFocus();
    }

    @Override
    public void login(boolean isLogin, String username, String pwd) {
        Log.e(TAG, "onViewClicked: user = " + username + " pwd = " + pwd);
        if (isLogin) {
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();

            Login lg = new Login(username, pwd);

            Intent intent = new Intent(this, Main2Activity.class);
            intent.putExtra("login", new Gson().toJson(lg));
            startActivity(intent);
        } else {
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
        }
    }
}
